#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/file.h>
#include <stdint.h>
#include <errno.h>
#include <sstream>
#include <string>
#include <fcntl.h>

int lockfile(int fd)
{  
    struct flock fk;  
    fk.l_type = F_WRLCK;
    fk.l_start = 0;
    fk.l_whence = SEEK_SET;
    fk.l_len = 0;
    return (fcntl(fd, F_SETLK, &fk));
}  

static const char * const pidfile = "onlyone.lock";

int main( int argc, char * arv[] )
{
	fprintf( stderr, "prcess(%d) start\n", getpid() );
	
	int32_t fd = open( pidfile, O_RDWR|O_CREAT, 0644 );
	if( fd < 0 )
	{
		fprintf( stderr, "open %s failed! %s\n", pidfile, strerror( errno ) );
		return -1;
	}
	
	//if( 0 != lockfile( fd ) )
	if( 0 != flock( fd, LOCK_EX | LOCK_NB ) )
	{
		fprintf( stderr, "process(%d) unable to acquire lock for %s\n", getpid(), pidfile );
		close( fd );
		return -1;
	}
	
	fprintf( stderr, "prcess(%d) write pid\n", getpid() );
	sleep( 3 );	
	std::ostringstream oss;
	oss << getpid() << std::endl;
	write( fd, oss.str().c_str(), oss.str().length() );
	
	close( fd );
	return 0;
}
